export class FileTransformInterceptor implements NestInterceptor { private async streamToString(multipartFile: MultipartFile): Promise {const stream = multipartFile.file;const chunks = [];return new Promise((resolve, reject) => { stream.on('data', (chunk) => {chunks.push(Buffer.from(chunk)); }); stream.on('error', (err) => {reject(err); }); stream.on('end', () => {return resolve(Buffer.concat(chunks).toString('utf8')); }); stream.on('limit', () => {reject(new BadRequestException('File size limit exceeded')); });}); } private validateAndGetFileType(filename: string, mimetype: string) {const nameSplits = filename.split('.');const extension = nameSplits[nameSplits.length - 1];const supportedTypes = [ { extension: 'json', mimetype: 'application/json' },];const typeCheckResult = find(supportedTypes, { extension }) || find(supportedTypes, { mimetype });if (!typeCheckResult) { throw new BadRequestException('File type not supported');}return typeCheckResult.type; } async intercept(context: ExecutionContext,next: CallHandler, ): Promise {const req = context.switchToHttp().getRequest();if (!req.isMultipart()) { throw new BadRequestException('Request must be multipart');}const multipartFile = await req.file();if (!multipartFile) { throw new BadRequestException('File required');}
this.validateAndGetFileType(multipartFile.filename, multipartFile.mimetype);const fileContents = await this.streamToString(multipartFile);
try { req.body = JSON.parse(fileContents);} catch (err) { throw new BadRequestException('Invalid JSON format');}return next.handle(); }}